package com.ximu.service_home.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ximu.service_base.result.Result;
import com.ximu.service_home.entity.PlatCommodity;
import com.ximu.service_home.entity.PlatOnetype;
import com.ximu.service_home.entity.PlatTwotype;
import com.ximu.service_home.service.PlatCommodityService;
import com.ximu.service_home.service.PlatOnetypeService;
import com.ximu.service_home.service.PlatTwotypeService;
import com.ximu.service_home.vo.PlatCommodityVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 平台端商品信息 前端控制器
 * </p>
 *
 * @author ximu
 * @since 2022-04-22
 */
@RestController
@RequestMapping("/service_home")
@CrossOrigin
@Api(tags = "首页API")
public class PlatCommodityController {

    @Autowired
    private PlatCommodityService platCommodityService;
    @Autowired
    private PlatOnetypeService platOnetypeService;
    @Autowired
    private PlatTwotypeService platTwotypeService;

    @ApiOperation(value = "所有商品列表")
    @GetMapping("findAllCommodity")
    public Result findAllCommodity(){
        List<PlatCommodity> list = platCommodityService.list(null);

        return Result.ok().data("items",list);
    }

    @ApiOperation(value = "分类查询商品列表")
    @GetMapping("typeFindCommodity/{type_id}")
    public Result typeFindCommodity(@ApiParam(name = "type_id",value = "分类id",required = true)
                                        @PathVariable int type_id){
        //构造条件
        QueryWrapper<PlatCommodity> wrapper = new QueryWrapper<>();
        wrapper.eq("type_id",type_id);
        //创建返回vo对象
        List<PlatCommodityVo> voList = new ArrayList<>();
        List<PlatCommodity> list = platCommodityService.list(wrapper);
        //提高域
        PlatOnetype one = null;
        PlatTwotype two = null;
        if (type_id>1000){
            two = platTwotypeService.getById(type_id);
        }else {
            one = platOnetypeService.getById(type_id);
        }
        for (PlatCommodity platCommodity:list) {
            PlatCommodityVo platCommodityVo = new PlatCommodityVo();
            //复制到vo
            BeanUtils.copyProperties(platCommodity,platCommodityVo);
            //判断二级分类是否不为空，不为空则查询一级分类，为空则直接设置一级分类的值
            if (Objects.nonNull(two)){
                one = platOnetypeService.getById(two.getTypeFather());
                platCommodityVo.setOneType(one.getTypeName());
                platCommodityVo.setTwoType(two.getTypeName());
            }else {
                platCommodityVo.setOneType(one.getTypeName());
            }
            voList.add(platCommodityVo);
        }

        return Result.ok().data("items",voList);
    }

}

